# coding=utf-8
from os import path
import sys
from time import sleep
from PySide6 import QtCore
from PySide6.QtWidgets import QApplication, QMessageBox, QWidget, QLabel, QLineEdit, QPushButton, QProgressBar, \
    QGridLayout, QStyle, QTextBrowser
from pyaria2 import Aria2RPC
from PySide6.QtCore import QProcess, QUrl, QThread, QObject, Slot, Signal
from ctypes import c_longlong as ll


class DownloadThread(QThread):
    resultReady = QtCore.Signal(dict)

    def __init__(self, urls):
        super().__init__()

        self.jsonrpc = Aria2RPC()
        self.gid = None
        self.downloadUrls = urls

    def quit(self):
        self.shutdown()

    def shutdown(self):
        self.jsonrpc.forceShutdown()

    def run(self):
        if self.gid is None:
            self.download()
        while self.jsonrpc.tellStatus(self.gid)["status"] in ['active', "complete"]:
            self.resultReady.emit(self.jsonrpc.tellStatus(self.gid))
            sleep(1)

    @Slot()
    def download(self):
        options = {}
        self.gid = self.jsonrpc.addUri(self.downloadUrls, options=options)

    @Slot()
    def pause(self):
        self.jsonrpc.pause(self.gid)

    @Slot()
    def unpause(self):
        self.jsonrpc.unpause(self.gid)
        self.run()

    @Slot()
    def stop(self):
        self.jsonrpc.remove(self.gid)

    @Slot()
    def debug(self):
        print(self.jsonrpc.getGlobalStat())


class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        # 设置属性
        self.resize(400, 300)
        self.setWindowTitle("测试Qt进度条和aria2的联合")
        # 注册组件
        self.labelUrl = QLabel("下载链接")
        self.lineEditorUrl = QLineEdit(
            "https://download.cnki.net/CAJViewer-x86_64-buildubuntu1604-210401.AppImage")
        self.labelProgress = QLabel("下载进度")
        self.downloadProgress = QProgressBar()
        self.textResult = QTextBrowser()
        self.buttonStart = QPushButton("开始")
        self.buttonPause = QPushButton("暂停")
        self.buttonUnpause = QPushButton("继续")
        self.buttonRemove = QPushButton("移除")
        self.buttonDebug = QPushButton("Debug")
        # 设置组件
        self.lineEditorUrl.setClearButtonEnabled(True)
        self.buttonStart.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.buttonPause.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        self.buttonUnpause.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.buttonRemove.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        # self.buttonPause.setDisabled(True)
        # self.buttonStop.setDisabled(True)
        # 添加组件
        self.layout = QGridLayout(self)
        self.layout.addWidget(self.labelUrl, 0, 0, 1, 1)
        self.layout.addWidget(self.lineEditorUrl, 0, 1, 1, 5)
        self.layout.addWidget(self.labelProgress, 1, 0, 1, 1)
        self.layout.addWidget(self.downloadProgress, 1, 1, 1, 5)
        self.layout.addWidget(self.textResult, 2, 0, 2, 5)
        self.layout.addWidget(self.buttonStart, 4, 0, 1, 1)
        self.layout.addWidget(self.buttonPause, 4, 1, 1, 1)
        self.layout.addWidget(self.buttonUnpause, 4, 2, 1, 1)
        self.layout.addWidget(self.buttonRemove, 4, 3, 1, 1)
        self.layout.addWidget(self.buttonDebug, 4, 4, 1, 1)
        # 添加组件功能

        # class函数

    @Slot(str)
    def updateProgress(self, value):
        self.downloadProgress.setMaximum(int(value['totalLength']))
        self.downloadProgress.setValue(int(value['files'][0]['completedLength']))
        if value["status"] == "complete":
            self.downloadProgress.setValue(int(value['totalLength']))

    shutdown_aria2 = Signal()

    @Slot()
    def clearProgress(self):
        self.downloadProgress.setValue(0)

    def closeEvent(self, event):
        if QMessageBox.question(self, "退出程序", "确定退出吗？") == QMessageBox.No:
            event.ignore()
        else:
            event.accept()
            self.shutdown_aria2.emit()


# - [x]: 在线程Thread1跑界面，再在Thread1中开一个进程跑aria2RPC伺服
# - [ ]: 在线程Thread2跑下载，获取下载状态，传递给界面的progressBar（信号与槽）
# - [ ]: 在Thread1中用按钮控制Thread2的下载（信号与槽）
# >> (It is safe to connect signals and slots across different threads)

if __name__ == "__main__":
    process_aria2 = QProcess()
    program = "aria2c.exe"
    arguments = ['--enable-rpc=true', '--allow-overwrite=false', '--max-overall-download-limit=1M']
    process_aria2.start(program, arguments)

    app = QApplication()
    w = MyWidget()

    dt = DownloadThread([w.lineEditorUrl.text()])

    dt.resultReady.connect(w.updateProgress)

    # w.buttonStart.clicked.connect(dt.download)
    w.buttonStart.clicked.connect(dt.start)

    w.buttonPause.clicked.connect(dt.pause)
    w.buttonUnpause.clicked.connect(dt.unpause)
    w.buttonRemove.clicked.connect(dt.stop)
    w.buttonRemove.clicked.connect(w.clearProgress)
    w.buttonDebug.clicked.connect(dt.debug)

    w.shutdown_aria2.connect(dt.quit)
    w.show()

    sys.exit(app.exec())
